package com.cloudfun.campusshare.repo;

import com.cloudfun.campusshare.common.constant.UserCouponStatus;
import com.cloudfun.campusshare.entity.UserCouponEntity;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by CodeGenerator on 2020/05/29
 */
public interface UserCouponRepo extends PagingAndSortingRepository<UserCouponEntity, String>, JpaSpecificationExecutor<UserCouponEntity> {

    List<UserCouponEntity> findAllByStatus(UserCouponStatus status);

    Long countAllByCreateTimeGreaterThanEqual(String createTimeStart);

    List<UserCouponEntity> findAllByIdIn(List<String> ids);

    long countAllByPromotionIdAndUserId(String promotionId, String userId);

    @Modifying
    @Transactional
    @Query("update UserCouponEntity set status=:status,useTime=:useTime,orderId=:orderId,orderNo=:orderNo where" +
            " id=:id and status='NOT_USED' and useTime is null and orderId is null and orderNo is null")
    int updateAfterUsed(@Param("id") String id, @Param("status") UserCouponStatus status, @Param("useTime") LocalDateTime useTime,
                        @Param("orderId") String orderId, @Param("orderNo") String orderNo);

    @Modifying
    @Transactional
    @Query("update UserCouponEntity set promotionId=:newPromotionId where promotionId=:oldPromotionId")
    int updatePromotionId(@Param("oldPromotionId") String oldPromotionId, @Param("newPromotionId") String newPromotionId);
}